var express = require('express')
var router = express.Router()

let leaseData = [
    {leaseId: '1', leaseBooks: '《舍得》', leaseName: '张三', identityCard: '100000000000000001', tel: '13700108864', leaseTime: '2021-09-10 至 2021-10-25'},
    {leaseId: '2', leaseBooks: '《活着》', leaseName: '李四', identityCard: '100000000000000002', tel: '13895267531', leaseTime: '2021-09-10 至 2021-10-25'},
    {leaseId: '3', leaseBooks: '《摆渡人》', leaseName: '王五', identityCard: '100000000000000003', tel: '16688256497', leaseTime: '2021-09-10 至 2021-10-25'},
    {leaseId: '4', leaseBooks: '《三体》', leaseName: '赵六', identityCard: '100000000000000004', tel: '15566428837', leaseTime: '2021-09-10 至 2021-10-25'},
 ]

router.get('/list', function (req, res, next) {
    if (!req.query.pageIndex) {
        res.send('缺少pageIndex')
    }

    if (!req.query.pageSize) {
        res.send('缺少pageSize')
    }

    let data = leaseData.filter(item => {
        return item.leaseBooks.includes(req.query.leaseBooks) && item.leaseName.includes(req.query.leaseName)
    })

    let start = (Number(req.query.pageIndex) - 1) * req.query.pageSize
    let end = Number(req.query.pageIndex) * req.query.pageSize

    res.send({
        pageIndex: req.query.pageIndex,
        pageSize: req.query.pageSize,
        total: data.length,
        data: data.slice(start, end)
    })
})

router.post('/add', function (req, res, next) {

    let data = {
        leaseId: Math.ceil(new Date().getTime() + Math.random() * 10000),
        leaseBooks: req.body.leaseBooks,
        leaseName: req.body.leaseName,
        identityCard: req.body.identityCard,
        tel: req.body.tel,
        leaseTime: req.body.leaseTime
    }

    leaseData.push(data)

    res.send({
        msg: '新增成功',
        code: 200,
        data: true
    })
})

router.put('/update', function (req, res, next) {
    if (!req.body.leaseId) {
        res.send('缺少id字段')

        return
    }

    let index = leaseData.findIndex(item => {
        return Number(item.leaseId) === Number(req.body.leaseId)
    })

    if (index < 0) {
        res.send({
            msg: '编辑失败，未通过leaseId找到对应数据',
            code: 500,
            data: false
        })

        return
    }

    leaseData[index] = Object.assign({}, req.body)

    res.send({
        msg: '编辑成功',
        code: 200,
        data: true
    })
})

router.delete('/delete', function (req, res, next) {
    if (!req.query.leaseId) {
        res.send('缺少leaseId字段')
    }

    let index = leaseData.findIndex(item => {
        return Number(item.leaseId) === Number(req.query.leaseId)
    })

    if (index < 0) {
        res.send({
            msg: '删除失败，未能通过leaseId找到对应数据',
            code: 500,
            data: false
        })
        return
    }

    leaseData.splice(index, 1)

    res.send({
        msg: '删除成功',
        code: 200,
        data: true
    })
})

module.exports = router